package com.thread.exe;

import java.io.PrintWriter;
import java.io.Writer;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class LogWriter {
	private static final int CAPACITY = 5;
	private final BlockingQueue<String> queue;
	private final LoggerThread logger;
	
	public LogWriter(PrintWriter writer) {
		super();
		this.queue = new LinkedBlockingQueue<>(CAPACITY);
		this.logger = new LoggerThread(writer);
	}
	
	public void log(String log) throws InterruptedException {
			queue.put(log);
	}


	private class LoggerThread extends Thread {
		private final PrintWriter writer;

		LoggerThread(PrintWriter writer) {
			super();
			this.writer = writer;
		}
		
		@Override
		public void run() {
			try {
				while(true) {
					writer.println(queue.take());
				}
			} catch (InterruptedException e) {
			} finally {
				writer.close();
			}
		}
	}
}
